<template>
  <div>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="medium"
      :label-width="labelWidth"
      class="form"
    >
      <el-form-item
        v-for="item in options"
        v-if="(item.type[2] || item.type[2] === 0)? form[item.type[1]] === item.type[2] : true"
        :key="item.key"
        :label="item.title"
        :prop="item.key"
        class="el-form-item"
      >
        <div v-if="$slots[item.key]">
          <slot :name="item.key" />
        </div>
        <div>
          <el-input
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'text' && form[item.type[1]] === item.type[2]) : item.type[0] === 'text'"
            v-model="form[item.key]"
            :maxlength="item.maxlength ? item.maxlength : 99999"
            style="width: 230px"
            :size="size"
            :placeholder="
              item.placeholder ? item.placeholder : '请输入' + item.title
            "
            :disabled="item.disabled"
            clearable
          />
          <el-input
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'textarea' && form[item.type[1]] == item.type[2]) : item.type[0] === 'textarea'"
            v-model="form[item.key]"
            :maxlength="item.maxlength ? item.maxlength : 99999"
            style="width: 230px"
            :size="size"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 6 }"
            :placeholder="
              item.placeholder ? item.placeholder : '请输入' + item.title
            "
            :disabled="item.disabled"
          />
          <el-switch
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'switch' && form[item.type[1]] == item.type[2]) : item.type[0] === 'switch'"
            v-model="form[item.key]"
            :size="size"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :disabled="item.disabled"
          />
          <el-date-picker
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'date' && form[item.type[1]] == item.type[2]) : item.type[0] === 'date'"
            v-model="form[item.key]"
            style="width: 230px"
            type="date"
            :placeholder="
              item.placeholder ? item.placeholder : '请选择' + item.title
            "
            value-format="yyyy-MM-dd"
            :size="size"
            :disabled="item.disabled"
            :picker-options="pickerOptions0(item)"
          />
          <el-date-picker
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'date-to-date' && form[item.type[1]] == item.type[2]) : item.type[0] === 'date-to-date'"
            v-model="form[item.key]"
            style="width: 230px"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :size="size"
            :disabled="item.disabled"
          />
          <el-input
            type="number"
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'number' && form[item.type[1]] == item.type[2]) : item.type[0] === 'number'"
            v-model="form[item.key]"
            :controls="false"
            style="width: 230px"
            :size="size"
            :disabled="item.disabled"
            @blur="((val)=>{changeBlur(val, item)})"
          />
          <el-select
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'select' && form[item.type[1]] === item.type[2]) : item.type[0] === 'select'"
            v-model="form[item.key]"
            style="width: 230px"
            :size="size"
            clearable
            :placeholder="
              item.placeholder ? item.placeholder : '请选择' + item.title
            "
            :disabled="item.disabled"
            @change="((val)=>{changeSelect(val, item)})"
          >
            <el-option
              v-for="data in item.option.data"
              :key="data[item.option.props.key]"
              :label="data[item.option.props.label]"
              :value="data[item.option.props.value]"
            />
          </el-select>
          <el-radio-group
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'radio' && form[item.type[1]] == item.type[2]) : item.type[0] === 'radio'"
            v-model="form[item.key]"
            :size="size"
            :disabled="item.disabled"
          >
            <el-radio
              v-for="data in item.option.data"
              :key="data[item.option.props.key]"
              :label="data[item.option.props.value]"
            >{{ data[item.option.props.label] }}
            </el-radio>
          </el-radio-group>
          <el-checkbox-group
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'checkbox' && form[item.type[1]] == item.type[2]) : item.type[0] === 'checkbox'"
            v-model="form[item.key]"
            :size="size"
            :disabled="item.disabled"
          >
            <el-checkbox
              v-for="data in item.option.data"
              :key="data[item.option.props.key]"
              :label="data[item.option.props.label]"
            >{{ data[item.option.props.label] }}
            </el-checkbox>
          </el-checkbox-group>
          <!--          <el-upload-->
          <!--            v-if="item.type[2]? (item.type[0] === 'file' && form[item.type[1]] == item.type[2]) : item.type[0] === 'file'"-->
          <!--            action="/bookkeeping/base/upload"-->
          <!--            multiple-->
          <!--            :headers="headers"-->
          <!--            :show-file-list="false"-->
          <!--            :on-success="handleAvatarSuccess"-->
          <!--            :disabled="item.disabled"-->
          <!--          >-->
          <!--            <img-->
          <!--              v-for="(item,index) in fileList"-->
          <!--              v-if="fileList.length>0"-->
          <!--              :key="index"-->
          <!--              :src="item.src"-->
          <!--              alt=""-->
          <!--              style="width: 178px; height: 178px; border-radius: 6px;"-->
          <!--              @click="setFileKey(item.key)"-->
          <!--            >-->
          <!--            <i-->
          <!--              v-else-->
          <!--              class="el-icon-plus avatar-uploader-icon"-->
          <!--              @click="setFileKey(item.key)"-->
          <!--            />-->
          <!--          </el-upload>-->
          <el-upload
            v-if="(item.type[2] || item.type[2] === 0)? (item.type[0] === 'file' && form[item.type[1]] == item.type[2]) : item.type[0] === 'file'"
            :disabled="item.disabled"
            class="upload-demo"
            action="/bookkeeping/base/upload"
            :headers="headers"
            multiple
            :limit="limit"
            accept=".jpg,.jpeg,.png,.pjpeg"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :on-exceed="handleExceed"
            :file-list="fileList"
            list-type="picture"
            style="width: 230px"
          >
            <el-button :disabled="item.disabled" size="small" type="primary">点击上传</el-button>
            <!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
          </el-upload>
        </div>
        <div v-if="item.info" class="info">{{ item.info }}</div>
      </el-form-item>
      <slot name="options" />
    </el-form>
    <div style="text-align: center">
      <el-button @click="clearValidate">取消</el-button>
      <el-button type="primary" @click="validate">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getImgs } from '@/api/revenueExpenditure'

export default {
  name: 'Index',
  props: {
    // 表单
    form: {
      type: Object,
      default: function() {
        return {}
      }
    },
    // 表单配置
    options: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 是否行内表单
    inline: {
      type: Boolean,
      default: function() {
        return false
      }
    },
    // 表单表头宽度
    labelWidth: {
      type: String,
      default: function() {
        return '120px'
      }
    },
    // 控件大小
    size: {
      type: String,
      default: function() {
        return 'medium'
      }
    },
    fileId: {
      type: Array
    }
  },
  data() {
    return {
      pickerOptions0: {},
      fileKey: '',
      limit: 3,
      headers: {},
      rules: {},
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      files: []
    }
  },
  created() {
    this.pickerOptions0 = function(item) {
      if (item.beforeToday || item.afterToday || item.customDate || item.customDateTwo) {
        return {
          disabledDate(time) {
            if (item.beforeToday) {
              // 今天之前
              return time.getTime() > Date.now() - 8.64e6
            } else if (item.afterToday) {
              // 今天之后
              return time.getTime() < Date.now() - 8.64e7
            } else if (item.customDate) {
              // 发生日期之前到今天之后
              return Date.now() - 8.64e6 < time.getTime() || time.getTime() < item.customDate
            } else if (item.customDateTwo) {
              // 发生日期之后
              return time.getTime() < item.customDateTwo
            } else {
              return
            }
          }
        }
      }
    }
  },
  mounted() {
    this.headers = {
      'Authorization': getToken()
    }
    // 动态添加验证
    this.addRules(this.options)
    // console.log('fileId', this.fileId)
    if (this.fileId && this.fileId.length > 0) {
      this.getImg()
    }
  },
  methods: {
    getImg() {
      this.fileId.forEach(v => {
        getImgs(v).then(res => {
          if (res.code === 0) {
            this.fileList.push({
              url: res.result.fileUrl,
              id: v
            })
            this.files.push({
              url: res.result.fileUrl,
              id: v
            })
          }
        })
      })
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList)
      this.files = fileList
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 999 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handleAvatarSuccess(res, file, fileList) {
      // console.log(res, 'res')
      // console.log(fileList, 'fileList')
      file.name = ''
      file.id = res.result.id
      this.files = fileList
    },
    // 选择select
    changeSelect(val, item) {
      // console.log(val, item)
      if (item.changeSelect) {
        this.$refs.form.clearValidate()
        this.$emit('changeSelect', val, item)
      }
    },
    // 输入框onblur
    changeBlur(val, item) {
      // console.log(val, item)
      if (item.changeBlur) {
        // 计算数量
        if (item.key === 'price' && this.form.amount && this.form.price) {
          this.form.quantity = parseInt(this.form.amount / this.form.price * 100) / 100
        }
        // 计算价格
        if (item.key === 'quantity' && this.form.amount && this.form.quantity) {
          this.form.price = parseInt(this.form.amount / this.form.quantity * 100) / 100
        }
      }
    },
    // 动态添加表单验证
    addRules(options) {
      for (let i = 0; i < options.length; i++) {
        // 判断是否需要添加验证
        if (options[i].rules) {
          // 判断用户是否已经自定义验证了
          // console.log('this.rules[options[i].key]', this.rules[options[i].key])
          if (!this.rules[options[i].key]) {
            // 动态生成验证方法
            const data = [
              {
                required: true,
                message: '',
                trigger: ''
              }
            ]
            // 动态添加验证方式：失去焦点触发/确认时触发
            if (options[i].type[0] === 'text' || options[i].type[0] === 'input' || options[i].type[0] === 'number') {
              data[0].message = '请输入' + options[i].title
              data[0].trigger = 'blur'
            } else {
              data[0].message = '请选择' + options[i].title
              data[0].trigger = 'blur'
            }
            // 触发vue更新
            this.$set(this.rules, options[i].key, data)
          }
        }
      }
      // 初始化完成清除一下表单验证规则
      this.$nextTick(function() {
        this.clearValidates()
      })
    },
    // 表单验证
    validate() {
      // console.log(this.form)
      // console.log('fileList', this.files)
      let isValidate = false
      this.$refs.form.validate(valid => {
        if (valid) {
          isValidate = true
          // 附件处理
          const arr = []
          for (let i = 0; i < this.files.length; i++) {
            arr.push(this.files[i].id)
          }
          this.form.fileId = arr
          // console.log(this.form, arr)
          this.$emit('validate')
        }
      })
      return isValidate
    },
    // 清楚表单验证
    clearValidates() {
      this.$refs.form.clearValidate()
    },
    // 清除表单验证
    clearValidate() {
      this.$refs.form.clearValidate()
      this.$emit('clearValidate')
    }
  }
}
</script>

<style scoped>
/*.form {*/
/*  display: flex;*/
/*  justify-content: flex-start;*/
/*  flex-wrap: wrap;*/
/*  align-items: center;*/
/*}*/

/*.el-form-item {*/
/*  width: 40%;*/
/*  margin-right: 20px;*/
/*  !*margin: 10px 20px;*!*/
/*}*/

/*>>> .el-upload {*/
/*  border: 1px dashed #d9d9d9;*/
/*  border-radius: 6px;*/
/*  cursor: pointer;*/
/*  position: relative;*/
/*  overflow: hidden;*/
/*  width: 178px;*/
/*  height: 178px;*/
/*}*/

/*.avatar-uploader-icon {*/
/*  font-size: 28px;*/
/*  color: #8c939d;*/
/*  width: 178px;*/
/*  height: 178px;*/
/*  line-height: 178px;*/
/*  text-align: center;*/
/*}*/

/*>>> .el-upload:hover {*/
/*  border-color: #409eff;*/
/*}*/

.info {
  line-height: 20px;
  color: red;
  font-size: 10px;
  height: 20px;
}
</style>
